package com.ruoyi.ewem.controller;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.utils.uuid.IdUtils;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.ewem.domain.Physical;
import com.ruoyi.ewem.domain.Product;
import com.ruoyi.ewem.domain.ProvinceCityDistrict;
import com.ruoyi.ewem.domain.Warehouse;
import com.ruoyi.ewem.service.IEwemPhysicalService;
import com.ruoyi.ewem.service.ProductService;
import com.ruoyi.ewem.service.ProvinceCityDistrictService;
import com.ruoyi.ewem.service.WarehouseService;
import com.ruoyi.ewem.domain.*;
import com.ruoyi.ewem.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @Author: Yanyanyu
 * @Date: 2024/7/27 10:07
 */
@RestController
@RequestMapping("product")
public class ProductController extends BaseController {

    @Autowired
    private ProductService productService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IEwemPhysicalService physicalService;

    @Autowired
    private ProvinceCityDistrictService provinceService;

    @Autowired
    private WarehouseService warehouseService;

    @Autowired
    private QualityService qualityService;

    @GetMapping("list")
    public TableDataInfo list(Product product){
        startPage();
        List<Product> list = productService.getList(product);


        for (Product product1 : list) {
            //获取成熟时间
            Date endTime = product1.getEndTime();
            //成熟时间与当前时间比较
            int i = endTime.compareTo(new Date());
            //判断值是否小于等于0 然后修改种植状态
            if(i <= 0){
                product1.setPlantStatus("1");
                productService.updateById(product1);
            }
        }

        return getDataTable(list);
    }


    @RequestMapping("addProduct")
    public AjaxResult addProduct(@RequestBody Product product){
        product.setProductNum(IdUtils.randomUUID());
        product.setCreateBy(SecurityUtils.getUsername());
        product.setCreateTime(new Date());
        productService.save(product);
        return success();
    }

    @RequestMapping("updateProduct")
    public AjaxResult updateProduct(@RequestBody Product product){

        product.setUpdateBy(SecurityUtils.getUsername());
        product.setUpdateTime(new Date());
        productService.updateById(product);
        return success();
    }

    @RequestMapping("delProduct/{productId}")
    public AjaxResult delProduct(@PathVariable Integer productId){
        productService.delProductById(productId);
        return success();
    }


    @RequestMapping("provinceList")
    public AjaxResult provinceList(){
        // 如果 Redis 不存在，就缓存到 Redis
        if (!redisTemplate.hasKey("provinceList")) {
            List<ProvinceCityDistrict> list = provinceService.list();
            redisTemplate.opsForValue().setIfAbsent("provinceList",list);
        }
        List<ProvinceCityDistrict> list = (List<ProvinceCityDistrict>) redisTemplate.opsForValue().get("provinceList");

        //配置
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();

        treeNodeConfig.setChildrenKey("children");
        treeNodeConfig.setIdKey("value");
        treeNodeConfig.setNameKey("label");
        //转换器
        List<Tree<String>> treeNodes = TreeUtil.build(list, "0", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getId()+"");
                    tree.setParentId(treeNode.getPid()+"");
                    tree.setName(treeNode.getName());
                });
        return AjaxResult.success(treeNodes);
    }


    @RequestMapping("addPhysical")
    public AjaxResult addPhysical(@RequestBody Physical physical){

        //根据批次查询是否质检
        LambdaQueryWrapper<Quality> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Quality::getBatchNum,physical.getBatchNum());
        Quality quality = qualityService.getOne(lambdaQueryWrapper);

        if(quality==null){
            return error("未质检，无法配送");
        }

        if(quality.getQualityResult().equals("1")){
            return error("质检不合格，无法配送");
        }

        if(quality.getQualityResult().equals("2")){
            return error("待质检，无法配送");
        }

        //根据批次修改配送状态
        LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Product::getBatchNum,physical.getBatchNum());
        Product product = productService.getOne(queryWrapper);
        product.setFlag("1");
        productService.updateById(product);

        //根据仓库id查询仓库地址
        Warehouse warehouse=warehouseService.getByWarehouseId(physical.getWarehouseId());
        physical.setEndName(warehouse.getAddress());

        physical.setPhysicalNum(IdUtils.randomUUID());
        physical.setCreateBy(SecurityUtils.getUsername());
        physical.setCreateTime(new Date());
        physicalService.save(physical);
        return success();
    }



    @RequestMapping("getBatchNum")
    public AjaxResult getBatchNum(){
        Random random = new Random();
        StringBuilder prefix = new StringBuilder();
        // 生成两个随机大写字母
        for (int i = 0; i < 2; i++) {
            prefix.append((char) (random.nextInt(26) + 'A'));
        }
        StringBuilder sb = new StringBuilder(prefix);
        // 生成 4 位数字
        for (int i = 0; i < 4; i++) {
            sb.append(random.nextInt(10));
        }
        System.out.println(sb);

        return AjaxResult.success(sb);
    }


    @RequestMapping("addQuality")
    public AjaxResult addQuality(@RequestBody Quality quality){

        LambdaQueryWrapper<Quality> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Quality::getBatchNum,quality.getBatchNum());
        Quality serviceOne = qualityService.getOne(queryWrapper);
        System.err.println(serviceOne);

        if(serviceOne == null) {
            LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Product::getBatchNum,quality.getBatchNum());
            Product one = productService.getOne(wrapper);

            quality.setProductId(one.getProductId());
            quality.setCreateBy(SecurityUtils.getUsername());
            quality.setCreateTime(new Date());
            qualityService.save(quality);
        } else if(serviceOne.getBatchNum().equals(quality.getBatchNum())){
            return error("该批次已质检，");
        }

        return success();
    }

}
